<template>
  <div class="daily-summary">
    <!-- 报表主体内容 -->
    <el-card shadow="hover" class="main-card">
      <!-- 汇总指标卡片 -->
      <div class="metric-cards">
        <el-row :gutter="16">
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="总销售额" 
              :value="formatCurrency(reportData.totalSales || 0)" 
              icon="Money"
            />
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="订单数量" 
              :value="reportData.totalOrders || 0" 
              icon="Document"
            />
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="客单价" 
              :value="formatCurrency(getAverageOrderValue)" 
              icon="DataAnalysis"
            />
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="日期" 
              :value="formatDate(reportData.date)" 
              icon="Calendar"
            />
          </el-col>
        </el-row>
        
        <!-- 添加退款信息 -->
        <el-row :gutter="16" v-if="reportData.refundAmount">
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="退款金额" 
              :value="formatCurrency(reportData.refundAmount || 0)" 
              icon="RefreshLeft"
              type="danger"
            />
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="退款订单数" 
              :value="reportData.refundOrders || 0" 
              icon="WarningFilled"
              type="danger"
            />
          </el-col>
          
          <el-col :xs="24" :sm="12" :md="6">
            <MetricCard 
              title="净销售额" 
              :value="formatCurrency((reportData.totalSales || 0) - (reportData.refundAmount || 0))" 
              icon="Wallet"
              type="success"
            />
          </el-col>
        </el-row>
      </div>

      <!-- 销售渠道数据 -->
      <div class="section-title">
        <h3>销售渠道分析</h3>
      </div>
      <el-table
        :data="reportData.salesByChannel || []"
        style="width: 100%"
        border
        stripe
        size="small"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :summary-method="getChannelSummaries"
        show-summary
      >
        <el-table-column prop="channelName" label="渠道名称" width="140" />
        <el-table-column prop="amount" label="销售金额" width="120" align="right">
          <template #default="scope">
            {{ formatCurrency(scope.row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="orders" label="订单数" width="80" align="right" />
        <el-table-column label="客单价" width="100" align="right">
          <template #default="scope">
            {{ formatCurrency(scope.row.amount / scope.row.orders) }}
          </template>
        </el-table-column>
        <el-table-column label="占比" min-width="150">
          <template #default="scope">
            <el-progress 
              :percentage="getSalesPercentage(scope.row.amount)" 
              :color="getRandomColor(scope.row.channelName)"
              :stroke-width="10"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 支付方式数据 -->
      <div class="section-title">
        <h3>支付方式分析</h3>
      </div>
      <el-table
        :data="reportData.salesByPaymentMethod || []"
        style="width: 100%"
        border
        stripe
        size="small"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :summary-method="getPaymentSummaries"
        show-summary
      >
        <el-table-column prop="method" label="支付方式" width="140">
          <template #default="scope">
            <el-tag size="small" effect="plain" :type="getPaymentMethodTagType(scope.row.method)">
              {{ getPaymentMethodName(scope.row.method) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" width="120" align="right">
          <template #default="scope">
            {{ formatCurrency(scope.row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="count" label="笔数" width="80" align="right" />
        <el-table-column label="占比" min-width="150">
          <template #default="scope">
            <el-progress 
              :percentage="getSalesPercentage(scope.row.amount)" 
              :color="getPaymentMethodColor(scope.row.method)"
              :stroke-width="10"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 热销商品数据 -->
      <div class="section-title">
        <h3>热销商品</h3>
      </div>
      <el-table
        :data="reportData.topProducts || []"
        style="width: 100%"
        border
        stripe
        size="small"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        height="300"
      >
        <el-table-column type="index" label="排名" width="60" />
        <el-table-column prop="name" label="商品名称" min-width="150" />
        <el-table-column prop="quantity" label="销售数量" min-width="90" align="right" />
        <el-table-column prop="amount" label="销售金额" min-width="120" align="right">
          <template #default="scope">
            {{ formatCurrency(scope.row.amount) }}
          </template>
        </el-table-column>
        <el-table-column label="均价" min-width="90" align="right">
          <template #default="scope">
            {{ formatCurrency(scope.row.amount / scope.row.quantity) }}
          </template>
        </el-table-column>
        <el-table-column label="销售占比" min-width="150">
          <template #default="scope">
            <el-progress 
              :percentage="getSalesPercentage(scope.row.amount)" 
              :color="getRandomColor(scope.row.name)"
              :stroke-width="10"
            />
          </template>
        </el-table-column>
      </el-table>

      <!-- 操作员销售数据 -->
      <div class="section-title">
        <h3>操作员销售分析</h3>
      </div>
      <el-table
        :data="reportData.salesByOperator || []"
        style="width: 100%"
        border
        stripe
        size="small"
        :header-cell-style="{ background: '#f5f7fa', color: '#606266' }"
        :summary-method="getOperatorSummaries"
        show-summary
      >
        <el-table-column prop="userName" label="操作员" min-width="120" />
        <el-table-column prop="amount" label="销售金额" min-width="120" align="right">
          <template #default="scope">
            {{ formatCurrency(scope.row.amount) }}
          </template>
        </el-table-column>
        <el-table-column prop="orders" label="订单数" min-width="90" align="right" />
        <el-table-column label="客单价" min-width="100" align="right">
          <template #default="scope">
            {{ formatCurrency(scope.row.amount / scope.row.orders) }}
          </template>
        </el-table-column>
        <el-table-column label="占比" min-width="120">
          <template #default="scope">
            <el-progress 
              :percentage="getSalesPercentage(scope.row.amount)" 
              :color="getRandomColor(scope.row.userName)"
              :stroke-width="10"
            />
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 报表说明 -->
      <div class="note-content compact-note">
        <el-tag type="info" effect="plain" size="small">
          <i class="el-icon-info"></i> 本报表显示 {{ formatDate(reportData.date) }} 的销售数据。数据来源：POS收银系统、线上支付系统
        </el-tag>
      </div>
    </el-card>
  </div>
</template>

<script setup name="DailySummary">
import { ref, computed, onMounted, defineExpose } from 'vue';
import { formatCurrency, formatDate } from '@/utils/formatters';
import MetricCard from './common/MetricCard.vue';

const props = defineProps({
  dateRange: {
    type: Array,
    required: true
  },
  loading: {
    type: Boolean,
    default: false
  },
  reportData: {
    type: Object,
    default: () => ({})
  },
  filterParams: {
    type: Object,
    default: () => ({})
  }
});

const emit = defineEmits(['refresh']);

// 计算客单价
const getAverageOrderValue = computed(() => {
  if (!props.reportData || !props.reportData.totalSales || !props.reportData.totalOrders) {
    return 0;
  }
  return props.reportData.totalSales / props.reportData.totalOrders;
});

// 获取销售额占比百分比
const getSalesPercentage = (amount) => {
  if (!props.reportData || !props.reportData.totalSales || !amount) {
    return 0;
  }
  return Math.round((amount / props.reportData.totalSales) * 100);
};

// 获取支付方式显示名称
const getPaymentMethodName = (method) => {
  const methods = {
    'wechat': '微信支付',
    'alipay': '支付宝',
    'cash': '现金',
    'card': '银行卡',
    'member': '会员卡',
    'coupon': '优惠券',
    'mixed': '混合支付',
    'unknown': '未知方式'
  };
  
  return methods[method] || method;
};

// 获取支付方式标签类型
const getPaymentMethodTagType = (method) => {
  const types = {
    'wechat': 'success',
    'alipay': 'primary',
    'cash': 'warning',
    'card': 'info',
    'member': 'danger',
    'coupon': '',
    'mixed': '',
    'unknown': ''
  };
  
  return types[method] || '';
};

// 获取支付方式颜色
const getPaymentMethodColor = (method) => {
  const colors = {
    'wechat': '#07C160',
    'alipay': '#1677FF',
    'cash': '#E6A23C',
    'card': '#409EFF',
    'member': '#F56C6C',
    'coupon': '#9254DE',
    'mixed': '#909399',
    'unknown': '#909399'
  };
  
  return colors[method] || '#409EFF';
};

// 生成随机颜色
const getRandomColor = (seed) => {
  // 基于字符串生成稳定的颜色
  let hash = 0;
  for (let i = 0; i < seed.length; i++) {
    hash = seed.charCodeAt(i) + ((hash << 5) - hash);
  }
  
  const colors = ['#409EFF', '#67C23A', '#E6A23C', '#F56C6C', '#909399', '#9254DE', '#36CFC9'];
  const index = Math.abs(hash) % colors.length;
  return colors[index];
};

// 计算渠道表合计行
const getChannelSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    
    if (column.property === 'amount') {
      const totalAmount = data.reduce((sum, item) => sum + item.amount, 0);
      sums[index] = formatCurrency(totalAmount);
    } else if (column.property === 'orders') {
      const totalOrders = data.reduce((sum, item) => sum + item.orders, 0);
      sums[index] = totalOrders;
    } else if (index === 3) { // 客单价列
      const totalAmount = data.reduce((sum, item) => sum + item.amount, 0);
      const totalOrders = data.reduce((sum, item) => sum + item.orders, 0);
      sums[index] = totalOrders ? formatCurrency(totalAmount / totalOrders) : 'N/A';
    } else {
      sums[index] = '';
    }
  });
  
  return sums;
};

// 计算支付方式表合计行
const getPaymentSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    
    if (column.property === 'amount') {
      const totalAmount = data.reduce((sum, item) => sum + item.amount, 0);
      sums[index] = formatCurrency(totalAmount);
    } else if (column.property === 'count') {
      const totalCount = data.reduce((sum, item) => sum + item.count, 0);
      sums[index] = totalCount;
    } else {
      sums[index] = '';
    }
  });
  
  return sums;
};

// 计算操作员表合计行
const getOperatorSummaries = (param) => {
  const { columns, data } = param;
  const sums = [];
  
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计';
      return;
    }
    
    if (column.property === 'amount') {
      const totalAmount = data.reduce((sum, item) => sum + item.amount, 0);
      sums[index] = formatCurrency(totalAmount);
    } else if (column.property === 'orders') {
      const totalOrders = data.reduce((sum, item) => sum + item.orders, 0);
      sums[index] = totalOrders;
    } else if (index === 3) { // 客单价列
      const totalAmount = data.reduce((sum, item) => sum + item.amount, 0);
      const totalOrders = data.reduce((sum, item) => sum + item.orders, 0);
      sums[index] = totalOrders ? formatCurrency(totalAmount / totalOrders) : 'N/A';
    } else {
      sums[index] = '';
    }
  });
  
  return sums;
};

// 刷新数据
const refreshData = () => {
  emit('refresh');
};

// 组件挂载时
onMounted(() => {
  // 检查reportData
  console.log('DailySummary组件挂载，reportData:', props.reportData);
});

// 显式暴露组件名称
defineExpose({
  componentName: 'DailySummary'
});
</script>

<style scoped>
.daily-summary {
  margin-bottom: 0;
}

.main-card {
  margin-bottom: 0;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.metric-cards {
  margin-bottom: 16px;
}

.section-title {
  margin: 16px 0 10px;
  display: flex;
  align-items: center;
}

.section-title h3 {
  font-size: 15px;
  margin: 0;
  padding-left: 8px;
  border-left: 3px solid #409EFF;
  line-height: 1.2;
  font-weight: 500;
}

:deep(.el-table) {
  font-size: 13px;
  margin-bottom: 20px;
}

:deep(.el-table th) {
  padding: 10px 0;
  font-weight: 500;
}

:deep(.el-table td) {
  padding: 8px 0;
}

.compact-note {
  margin-top: 16px;
  font-size: 12px;
}

@media screen and (max-width: 768px) {
  .metric-cards {
    margin-bottom: 15px;
  }
  
  .section-title h3 {
    font-size: 14px;
  }
}
</style> 